package com.travel.travel_springboot_web.service;

import com.travel.travel_springboot_web.entity.Goods;
import com.travel.travel_springboot_web.entity.GoodsImage;
import com.travel.travel_springboot_web.mapper.GoodsMapper;
import com.travel.travel_springboot_web.mapper.GoodsImageMapper;
import com.travel.travel_springboot_web.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class GoodsService {
    
    private static final Logger logger = LoggerFactory.getLogger(GoodsService.class);
    
    @Autowired
    private GoodsMapper goodsMapper;
    
    @Autowired
    private GoodsImageMapper goodsImageMapper;
    
    @Autowired
    private FileUtil fileUtil;
    
    @Transactional
    public Goods createGoods(Goods goods) {
        logger.info("Starting to create goods: {}", goods.getTitle());
        logger.info("Received imageUrls: {}", goods.getImageUrls());
        
        try {
            // 设置默认值
            if (goods.getSales() == null) {
                goods.setSales(0);
            }
            if (goods.getStatus() == null) {
                goods.setStatus(1);
            }
            
            // 设置主图（使用第一张图片作为主图）
            if (goods.getImageUrls() != null && !goods.getImageUrls().isEmpty()) {
                goods.setCoverImage(goods.getImageUrls().get(0));
                logger.info("Set cover image: {}", goods.getCoverImage());
            } else {
                logger.warn("No imageUrls provided, cover_image will be null");
            }
            
            // 打印完整的商品信息
            logger.info("Inserting goods: title={}, desc={}, coverImage={}, price={}, stock={}, status={}, sales={}", 
                    goods.getTitle(), goods.getDesc(), goods.getCoverImage(), 
                    goods.getPrice(), goods.getStock(), goods.getStatus(), goods.getSales());
            
            // 1. 插入商品基本信息
            int result = goodsMapper.insert(goods);
            logger.info("Goods basic info inserted, ID: {}, Result: {}, CoverImage: {}", 
                    goods.getId(), result, goods.getCoverImage());
            
            // 2. 处理商品图片
            if (goods.getImageUrls() != null && !goods.getImageUrls().isEmpty()) {
                logger.info("Found {} images to save", goods.getImageUrls().size());
                int sort = 0;
                for (String imageUrl : goods.getImageUrls()) {
                    GoodsImage goodsImage = new GoodsImage();
                    goodsImage.setGoodsId(goods.getId());
                    goodsImage.setImageUrl(imageUrl);
                    goodsImage.setSort(sort++);
                    
                    int imageResult = goodsImageMapper.insert(goodsImage);
                    logger.info("Image saved for goods {}: {}, Result: {}", 
                            goods.getId(), imageUrl, imageResult);
                }
            } else {
                logger.warn("No images found for goods: {}", goods.getId());
            }
            
            logger.info("Goods creation completed: {}", goods.getId());
            return goods;
            
        } catch (Exception e) {
            logger.error("Error creating goods: ", e);
            throw new RuntimeException("Failed to create goods: " + e.getMessage());
        }
    }
    
    // 添加新方法：保存单个图片
    public void saveImage(GoodsImage goodsImage) {
        logger.info("Saving image to database: {}", goodsImage.getImageUrl());
        goodsImageMapper.insert(goodsImage);
    }
    
    public List<Goods> getAllGoods() {
        try {
            logger.info("Getting all goods list");
            List<Goods> goodsList = goodsMapper.findAll(null);
            logger.info("Found {} goods", goodsList.size());
            return goodsList;
        } catch (Exception e) {
            logger.error("Error getting all goods list: ", e);
            throw new RuntimeException("获取商品列表失败: " + e.getMessage());
        }
    }
    
    @Transactional
    public boolean deleteGoods(Long id, boolean isSoftDelete) {
        logger.info("Deleting goods with ID: {}, soft delete: {}", id, isSoftDelete);
        
        try {
            // 检查商品是否存在
            if (goodsMapper.checkExists(id) == 0) {
                logger.warn("Goods not found with ID: {}", id);
                return false;
            }
            
            int result;
            if (isSoftDelete) {
                // 逻辑删除
                result = goodsMapper.softDeleteById(id);
                logger.info("Soft deleted goods with ID: {}, result: {}", id, result);
            } else {
                // 1. 获取商品图片URL列表
                List<String> imageUrls = goodsImageMapper.findByGoodsId(id);
                logger.info("Found {} images to delete for goods ID: {}", 
                        imageUrls.size(), id);
                
                // 2. 删除本地图片文件
                fileUtil.deleteFiles(imageUrls);
                logger.info("Deleted local image files for goods ID: {}", id);
                
                // 3. 删除数据库中的图片记录
                goodsImageMapper.deleteByGoodsId(id);
                logger.info("Deleted image records for goods ID: {}", id);
                
                // 4. 删除商品记录
                result = goodsMapper.deleteById(id);
                logger.info("Hard deleted goods with ID: {}, result: {}", id, result);
            }
            
            return result > 0;
        } catch (Exception e) {
            logger.error("Error deleting goods with ID: " + id, e);
            throw new RuntimeException("Failed to delete goods: " + e.getMessage());
        }
    }
    
    @Transactional
    public boolean updateGoods(Goods goods) {
        logger.info("Updating goods with ID: {}", goods.getId());
        
        try {
            // 检查商品是否存在
            if (goodsMapper.checkExists(goods.getId()) == 0) {
                logger.warn("Goods not found with ID: {}", goods.getId());
                return false;
            }
            
            // 更新商品基本信息
            int result = goodsMapper.update(goods);
            logger.info("Updated goods basic info, result: {}", result);
            
            // 更新商品图片
            if (goods.getImageUrls() != null && !goods.getImageUrls().isEmpty()) {
                // 删除旧的图片记录
                goodsImageMapper.deleteByGoodsId(goods.getId());
                logger.info("Deleted old images for goods ID: {}", goods.getId());
                
                // 插入新的图片记录
                int sort = 0;
                for (String imageUrl : goods.getImageUrls()) {
                    GoodsImage goodsImage = new GoodsImage();
                    goodsImage.setGoodsId(goods.getId());
                    goodsImage.setImageUrl(imageUrl);
                    goodsImage.setSort(sort++);
                    
                    goodsImageMapper.insert(goodsImage);
                    logger.info("Inserted new image: {} for goods ID: {}", imageUrl, goods.getId());
                }
            }
            
            return result > 0;
        } catch (Exception e) {
            logger.error("Error updating goods: ", e);
            throw new RuntimeException("Failed to update goods: " + e.getMessage());
        }
    }
    
    public List<Goods> getGoodsList(String keyword) {
        try {
            logger.info("Getting goods list with keyword: {}", keyword);
            List<Goods> goodsList = goodsMapper.findAll(keyword);
            logger.info("Found {} goods", goodsList.size());
            return goodsList;
        } catch (Exception e) {
            logger.error("Error getting goods list: ", e);
            throw new RuntimeException("获取商品列表失败: " + e.getMessage());
        }
    }
} 